package com.doge.walknovel.business.reader.menus

import android.os.Bundle
import android.view.*
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.doge.wnpro.R
import com.doge.walknovel.api.model.NovelDetailInfo
import com.doge.walknovel.api.model.ChapterInfo
import com.doge.walknovel.business.novel.NovelDetailViewModel
import com.doge.walknovel.business.novel.NovelDetailViewModelFactory
import com.doge.walknovel.business.novel.NovelRefer
import com.doge.walknovel.business.reader.ReaderViewModel
import com.doge.walknovel.business.reader.ReaderViewModelFactory
import com.doge.walknovel.core.BaseDialogFragment
import com.doge.walknovel.core.base.adapters.ITEM_CLICKED
import com.doge.walknovel.core.base.isRefreshing
import com.doge.wnpro.databinding.DialogFragmentReaderChapterBinding
import com.doge.walknovel.utils.*

class ReaderChapterDialogFragment : BaseDialogFragment() {
    private var innerBinding: DialogFragmentReaderChapterBinding? = null
    private val binding get() = innerBinding!!
    override val hasShadow = true
    private val refer by lazy { arguments?.getString(NovelRefer.EXTRA_REFER)!! }
    private val referId by lazy { arguments?.getInt(NovelRefer.EXTRA_REFER_ID) }
    private val novelId by lazy { arguments?.getInt(EXTRA_NOVEL_ID)!! }
    private val bookViewModel by activityViewModels<NovelDetailViewModel> {
        NovelDetailViewModelFactory(novelId, "readerChapter$refer", referId)
    }
    private val viewModel by activityViewModels<ReaderViewModel> {
        ReaderViewModelFactory(novelId)
    }
    private val adapter by lazy { ReaderChapterAdapter() }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        innerBinding =
            innerBinding ?: DialogFragmentReaderChapterBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.outside.setOnClickCallback {
            dismissAllowingStateLoss()
        }
        binding.recyclerView.itemAnimator = null
        binding.recyclerView.layoutManager = LinearLayoutManager(binding.recyclerView.context)
        binding.recyclerView.adapter = adapter
        adapter.setListener(::handleAdapterCallback)
        binding.refreshLayout.setColorSchemeResources(R.color.pull_refresh)
        binding.refreshLayout.setOnRefreshListener {
            viewModel.requestChapters()
        }
        viewModel.chapterLoading.observe(viewLifecycleOwner) {
            binding.refreshLayout.isRefreshing = it.isRefreshing()
        }
        viewModel.chapterDataList.observe(this) {
            adapter.submitList(it)
        }
        bookViewModel.bookDetail.observe(viewLifecycleOwner) {
            updateNovelInfo(it)
        }
    }

    private fun handleAdapterCallback(action: String, item: Any?) {
        when (action) {
            ITEM_CLICKED -> {
                viewModel.scrollToChapter((item as? ChapterInfo?)?.chapterId)
                dismissAllowingStateLoss()
            }
        }
    }

    private fun updateNovelInfo(data: NovelDetailInfo?) {
        binding.cover.load(
            data?.coverUrl,
            R.drawable.shape_f7f7f7_8,
            transformation = RoundedCorners8,
            width = 48.dp,
            height = 68.dp
        )
        binding.name.text = data?.title
        binding.author.text = data?.author
    }

    override fun onDestroyView() {
        super.onDestroyView()
        binding.outside.setOnClickListener(null)
        binding.refreshLayout.setOnRefreshListener(null)
        binding.recyclerView.adapter = null
        adapter.setListener(null)
        innerBinding = null
    }

    override fun setWindow(win: Window) {
        win.setWindowAnimations(R.style.Animation_Bottom_Rising)
        win.decorView.setPadding(0, 0, 0, 0)
        val lp = win.attributes
        lp.width = WindowManager.LayoutParams.MATCH_PARENT
        lp.height = WindowManager.LayoutParams.MATCH_PARENT
        win.attributes = lp
        win.setGravity(Gravity.BOTTOM)
    }

    companion object {
        private const val EXTRA_NOVEL_ID = "novelId"
        fun newInstance(novelId: Int,
                        refer: String, referId: Int? = null): ReaderChapterDialogFragment {
            return ReaderChapterDialogFragment().apply {
                arguments = Bundle().apply {
                    putInt(EXTRA_NOVEL_ID, novelId)
                    putString(NovelRefer.EXTRA_REFER, refer)
                    referId?.let { putInt(NovelRefer.EXTRA_REFER_ID, referId) }
                }
            }
        }
    }
}